#!/usr/bin/env bash
#
# line for crontab -e (-r delete)
# * * * * * sh ~/chk.sh > ~/chk.log
# 0 * * * * sh ~/chk.sh > ~/chk.log



VOLUME=/Volumes/My\ Passport
# time in minutes
TIME=10080
#FAILURES=40

BAREBACKUP_HOME=/Volumes/Work/Backups/BareBackup
MSG_START="Automatic Backup in progress"
MSG_OK="Automatic Backup complete"
MSG_KO="Backup is older than a week
Please plug the drive"

if [ -d "$VOLUME" ]
	then
	/usr/bin/osascript $BAREBACKUP_HOME/BareBackupGrowler.scpt "BareBackup" "BareBackup" "$MSG_START" 
	echo `date` ": launching backup"
	rsync -aE --delete /Volumes/Work/Backups "$VOLUME/Backups/rsync_mirror"
	echo "done 1"
	rsync -aE --delete ~/Documents "$VOLUME/Backups/rsync_mirror"
	echo "done 2"
	rsync -aE --size-only /Volumes/Work/vm "$VOLUME/"
	echo `date` ": finished backup"
	/usr/bin/osascript $BAREBACKUP_HOME/BareBackupGrowler.scpt "Backup Complete" "BareBackup" "$MSG_OK" 
	if [ -e "$BAREBACKUP_HOME/failed.log" ]
	then
		rm $BAREBACKUP_HOME/failed.log
	fi
else
	echo `date` "can not launch backup"
	if [ -e "$BAREBACKUP_HOME/failed.log" ]
	then
		#echo found
		#ct=`cat failed.log`
		#ct=`echo 0$ct+1|bc`
		#echo "failed $ct times"
		#echo "$ct" > failed.log
		#if [ $ct -gt $FAILURES ]
		#then
		#	echo "issue warning"
		#fi
		if [ -e "$BAREBACKUP_HOME/paused.log" ]
		then
			echo "program in pause mode, failure ignored"
		else
			find . -iname "$BAREBACKUP_HOME/failed.log" -mmin +$TIME -exec /usr/bin/osascript $BAREBACKUP_HOME/BareBackupGrowler.scpt "Backup Failed" "BareBakup" "$MSG_KO" \;
		fi
	else
		echo `date` > $BAREBACKUP_HOME/failed.log	
	fi
fi
